﻿var cellDgnEvent = {
  onSelChange: function (obj, info) {

  },
  onChange: function (obj, info) {

  },
  onCellDoubleClick: function (obj, info) {
    var cellP = cn.getCurCellPlus();
    var tag = cn.getCurCellPlus().selection().tag();
    if (tag && tag.indexOf("cus:bsd") >= 0) {
      var bd = cm.strSplit(tag, ":");
      var ret = yddser.getGroupBaseData(bd[2], bd[3], 1);
      if (cm.dataOk(ret)) {
        cn.getCurCellPlus().selection().cellType(new JsTreeCellType(ret.data));
      }
      else {
        cm.myAlert(ret.msg);
      }
    }
  },
  onLeaveCell: function (obj, info) {

  },
  openForm: function (e, data) {
    cm.loadingDlg(true);
    var cpl = cn.openForm(e, data);
    cn.setCplFormTableArrPos(cpl, function (cpsheet) {
      cpsheet.readonly(true);
    }, function (cprg) {
      cprg.readonly(false);
    });
    cm.loadingDlg(false);
  },
  openFormById: function (e, formId) {
    var ref = $('.cube_dimension_tree').jstree(true);
    var node = ref.get_node(formId);
    var tabData = cn.openForm(e, null, node.original);
    if ( tabData == null ){
      tabData = cn.getTabCell(formId);
    }
    cn.setCplFormTableArrPos(tabData.cellPlus, function (cpsheet) {
      cpsheet.readonly(true);
    }, function (cprg) {
      cprg.readonly(false);
    });
    return tabData;
  }
};

$(function () {
  $('.nav-user-info').mouseover(function () {
    $(this).parent().addClass('am-active am-dropdown-flip');
    $(this).next().attr('ishover', true);
  });

  $('.nav-user-info').mouseout(function () {
    var self = this;
    $(self).next().attr('ishover', false);
    setTimeout(function () {
      if ($(self).next().attr('ishover') == 'false') {
        $(self).parent().removeClass('am-active am-dropdown-flip');
      }
    }, 100);
  });

  $('.am-topbar-right .am-dropdown-content').mouseover(function () {
    $(this).attr('ishover', true);
  });

  $('.am-topbar-right .am-dropdown-content').mouseout(function () {
    var self = this;
    $(self).attr('ishover', false);
    setTimeout(function () {
      if ($(self).attr('ishover') == 'false') {
        $(self).parent().removeClass('am-active am-dropdown-flip');
      }
    }, 100);
  })
});

var user = {};
$(document).ready(function () {
  reloadBizPackForm();
  var $chromeTabsExampleShell = $('.chrome-tabs-shell')
  chromeTabs.init({
    $shell: $chromeTabsExampleShell,
    minWidth: 45,
    maxWidth: 160,
    fnTabClick: cn.tabClick,
    fnTabClose: cn.tabClose
  });

  user = yddser.getCurUser();
  $('.nav-user-info').html(user.data.userName + '<span class="am-icon-user"></span>');

  $chromeTabsExampleShell.bind('chromeTabRender', function () {
    var $currentTab = $chromeTabsExampleShell.find('.chrome-tab-current');
    if ($currentTab.length && window['console'] && console.log) {
      //console.log('Current tab index', $currentTab.index(), 'title', $.trim($currentTab.text()),
      // 'data', $currentTab.data('tabData').data);
    }
    if ($currentTab.length == 0) {
      $('#workspace_toolbar_panel').hide();
      $('#chrome-tabs-shell-panel').hide();
      $('.container').css('background', 'url(../main/newLogin_files/resources/images/bg.jpg) no-repeat');
    }
  });

  $('.cube_dimension_tree.dimension_tree').on('select_node.jstree', function (node, ele) {
    var uid = ele.node.id;
    if (cm.strStartWith(uid, 'pk')) {
      return;
    }
    $('#chrome-tabs-shell-panel').show();
    $('#workspace_toolbar_panel').show();
    $('.container').css('background', 'none');
    var rs = cn.getTabId(uid);
    if (rs) {
      rs.click();
    } else {
      // var tabName = $('#' + ele.node.id + ' > a').text();
      // var tabData = cn.genTabData("", tabName, {type: 'local', id: uid});
      // cn.addTab(tabData);
      var cpl = cn.openForm(null, ele);
      cn.setCplFormTableArrPos(cpl, function (cpsheet) {
        cpsheet.readonly(false);
      }, function (cprg) {
        cprg.readonly(true);
      });
    }
  }).on('hover_node.jstree',
    function (node, ele) {
      if ($('#' + ele.node.id + ' > div').find('.operators').length == 0) {
        var settings = $('<i class="am-icon-cog"></i>');
        var isEnter = false;
        settings.on('click', function (e) {
          e.stopPropagation();
          btPop.$data.nodeId = ele.node.id;
          btPop.$data.curNode = ele.node;
          $('#business-tooltips').css({'left': e.clientX - 20, 'top': e.clientY + 5}).show();
        }).on('mouseout', function () {
          setTimeout(function () {
            if ($('#business-tooltips').attr('ishover') == 'false') {
              $('#business-tooltips').hide();
            }
          }, 500);
        });

        var operators = $('<span class="operators"></span>');
        operators.append(settings);

        $('#' + ele.node.id + ' > div').append(operators);
      } else {
        $('#' + ele.node.id + ' > div').find('.operators').show();
      }
    }).on('dehover_node.jstree', function (node, ele) {
    var ref = $('.cube_dimension_tree.dimension_tree').jstree(true);
    $('#' + ele.node.id + ' > div').find('.operators').hide();
  }).jstree({
    "core": {
      "animation": 0,
      "check_callback": true,
      'force_text': true,
      // "themes" : { "stripes" : true },
      'data': {}
    },
    "search": {
      "show_only_matches": true
    },
    "types": {
      "#": {"max_children": 1, "max_depth": 4, "valid_children": ["root"]},
      "root": {"icon": "./img/folder.png", "valid_children": ["default"]},
      "default": {"valid_children": ["default", "file"]},
      "file": {"icon": "./img/file.png", "valid_children": []}
    },
    "plugins": ["search", "types", "wholerow"]
  });


  var gvc = null, gvc2 = null;
  $('.ydd-icon-btn').on('click', function (e) {
    var attrVal = $(e.target).attr("operatetype");
    if (attrVal == 'newpack' || attrVal == 'newform' || attrVal == 'newlocal') {
      var title = "", styleData = "";
      if (attrVal == 'newlocal') {
        var dd = cm.getCurDatetime();
        var tabData = cn.genTabData("", "local", {type: 'local', id: "local" + cm.dtToLong()});
        cn.addTab(tabData);
      }
    }
    else if (attrVal == 'clearinput') {
      $(e.target).parent().find('.ydd-searh-input').val('');
    }
  });

  $('.ydd-pack').on('click', function (e) {

    if ($(e.target).hasClass('data-am-modal-confirm')) {
      var pack = {};
      pack.name = $('#InputPackName').val();
      if (pack != null) {
        var ret = yddser.addOrUpdatePack(pack).data;
        cn.yddToJstree(ret);
        var ref = $('.cube_dimension_tree').jstree(true);
        var ddd = ref.create_node("#", ret, 'first');
      }
    }
  });

  $('.ydd-form').on('click', function (e) {

    if ($(e.target).hasClass('data-am-modal-confirm')) {
      var data = gvc.getSheet(0).getPrefixVarObjJs('Ref$');
      var CurrentNode = $('.cube_dimension_tree').jstree(true).get_selected(true);
      var form = yddser.addOrUpdateForm({
        name: formName,
        type: data.formType,
        packId: CurrentNode[0].original.oid
      }).data;
      cn.yddToJstree(form);
      var ref = $('.cube_dimension_tree').jstree(true);
      var ret = ref.create_node(CurrentNode[0], form, 'first');
      var tabData = cn.genTabData("", ret.text, ret);
      cn.addTab(tabData);
    }
  });

  $('.ydd-user').on('click', function (e) {

    if ($(e.target).hasClass('data-am-modal-confirm')) {
      var data = gvc.getSheet(0).getPrefixVarObjJs('Ref$');
      var user = yddser.addOrUpdateUser(data).data;
      cn.yddToJstree(user);
      var ref = $('#jtree-user').jstree(true);
      var CurrentNode = $('.cube_dimension_tree').jstree(true).get_selected(true);
      var ret = ref.create_node(CurrentNode[0], user, 'first');
    }
  });
  $('.tabbar-item').on('mouseover', function (e) {

    var vv = $('.tabbar-item.active');
    targetCon = vv.attr('data-target');
    $('.' + targetCon).addClass('hideimportant');
    vv.removeClass('active');

    $(e.target).addClass('active');
    var targetCon = $(e.target).attr('data-target');
    $('.' + targetCon).removeClass('hideimportant');

  }).on('mouseout', function (e) {

  });

  //$('#J-subtable-drop').on('mouseover', function (e) {
  //    $('#J-subtable-drop').dropdown('open');
  //}).on('mouseleave', function (e) {
  //    $('#J-subtable-drop').dropdown('close');
  //});

  //$('#J-finddata-drop').on('mouseover', function (e) {
  //    $('#J-finddata-drop').dropdown('open');
  //}).on('mouseleave', function (e) {
  //    $('#J-finddata-drop').dropdown('close');
  //});

  //$('.ydd-dropdown').on('mouseover', function (e) {

  //    if (!$(e.currentTarget).hasClass('am-active')) {
  //        var vv = $(e.currentTarget).find('.am-dropdown-toggle');
  //        vv.click();
  //    }
  //}).on('mouseleave', function (e) {

  //    //$('#J-font-family-drop').dropdown('close');
  //    if ($(e.currentTarget).hasClass('am-active')) {
  //        var vv = $(e.currentTarget).find('.am-dropdown-toggle');
  //        vv.click();
  //    }
  //});

  $('#newDept-getDept-Btn').click(function () {
    showDeptUserModal("", function (data, selDepts, selUsers) {
      for (var i = 0; i < selDepts.length; i++) {
        if (selDepts[i].name != null) {
          $('#newDept-getDept').val(selDepts[i].name);
          $('#newDept-getDept').attr("deptCode", selDepts[i].deptCode);
          $('#newDept-getDept').attr("deptId", selDepts[i].id);
        }
      }

    }, "department");

  });

  $('.ydd-dropdown').on('click', function (e) {
    if ($(e.target).attr('data-type') == 'item') {
      var ns = GcSpread.Sheets;
      if ($(e.currentTarget).attr("data-type") == "sub-table") {
        $('#J-subtable-drop').dropdown('close');
      }
    }
  });

  var $toggleButton = $('#doc-single-toggle');
  $toggleButton.on('click', function () {
    setButtonStatus();
  });

  function setButtonStatus() {
    var status = $toggleButton.hasClass('am-active') ? '未激活' : '激活';
    $('#doc-single-toggle-status').text(status);
  }


  var pl;
  $('#business-tooltips').hover(function () {
    $(this).attr('ishover', true);
  }, function () {
    $(this).attr('ishover', false);
  }).mouseleave(function () {
    var self = this;
    if (pl) {
      clearTimeout(pl);
    }
    var pl = setTimeout(function () {
      if ($(self).attr('ishover') == 'false') {
        btPop.$data.showBtns = true;
        $(self).hide();
      }
    }, 500);
  });

  $('.dpt-search .J-dimension-search').click(function () {
    if ($('.dpt-search .text').hasClass('hide')) {
      $('.dpt-search .text').removeClass('hide');
      $('.dpt-search .text').next().addClass('hide');

      $('.dpt-search input').val('');
      $('#departments').jstree(true).clear_search();
    } else {
      $('.dpt-search .text').addClass('hide');
      $('.dpt-search .text').next().removeClass('hide');
    }
  });

  var dptTo;
  $('.dpt-search input').keyup(function () {
    var self = this;
    if (dptTo) {
      clearTimeout(dptTo);
    }
    dptTo = setTimeout(function () {
      var v = $(self).val();
      $('#departments').jstree(true).search(v);
    }, 250);
  });

  $('.dpt-search .J-search-clear').click(function () {
    $(this).prev().val('');
    $('#departments').jstree(true).clear_search();
  });

  // 设置数据  auth.$data.users = [],   auth.$data.departments = []
  var workspace_toolbar = new Vue({
    el: '.workspace_toolbar',
    data: {
      gridColumns: [],
      gridData: [],
      quickDateNum: 0,
    },
    methods: {
      open: function (u) {
        $('#J-finddata-drop').dropdown('close');
        var reqResData = yddser.getFormData(u.dataIndex).data;
        var cpl = cn.getCurTabForm().cellPlus;
        cn.resetForm(cpl);
        cn.setCplFormData(cpl, reqResData);
      },
      newFormData: function () {
        var tabData = cn.getCurTabForm();
        cm.myAlertFunc("是否放弃当前表单修改,创建新表单?", "", function () {
          cn.resetForm();
          cn.setAutoCodeRg(tabData.cellPlus, 1);
        });
      },
      saveFormData: function () {
        var tabData = cn.getCurTabForm();
        cn.setAutoCodeRg(tabData.cellPlus, 2);
        var retD = yddser.addOrUpdateFormData(tabData.cellPlus, "", 0);

        if (cm.dataOk(retD)) {
          cm.myAlert("保存成功");
          cn.resetForm();
        }
        else {
          cm.myAlert(retD.msg);
        }
      },
      saveFormDataAsNew: function () {
        var tabData = cn.getCurTabForm();
        cn.setAutoCodeRg(tabData.cellPlus, 2);
        var retD = yddser.addOrUpdateFormData(tabData.cellPlus, "", 1);
        if (cm.dataOk(retD)) {
          cm.myAlert("保存成功");
          cn.resetForm();
        }
        else {
          cm.myAlert(retD.msg);
        }
      },
      insertSubItem: function () {
        var formData = cn.getCurTabForm();
        var tableArr = formData.cellPlus.formObj.tableArr;
        var cp = formData.cellPlus;
        var sel = cp.selection();

        for (var i = 0; i < tableArr.length; i++) {
          if (tableArr[i].tableType == 2) {
            var htRg = "RD:HTRG:" + tableArr[i].oid;
            htRg = cp.getRangeByCustomVar(htRg);
            if (htRg.isRgInThis(sel)) {
              htRg.htRgAppendItem(sel, 1, null, function (retCom, num, dir) {
                var curRg = retCom.curHTRgOne;
                var offsetArr = retCom.offsetArr;
                var headRg = retCom.headRg;
                var newOne = curRg.cloneNew();

                for (var i = 1; i <= num; i++) {
                  if (dir == 4) {
                    newOne.offsetBlock(1, 0);
                    var did = yddser.getNewId('did');
                    newOne.genOffsetRg(retCom.offsetArr[0]).tag(did.data);
                  }
                  else if (dir == 2) {
                    newOne.offsetBlock(-1, 0);
                    var did = yddser.getNewId('did');
                    newOne.genOffsetRg(retCom.offsetArr[0]).tag(did.data);
                  }
                }
              });
              return;
            }
          }
        }
        cm.myAlert("未发现子表数据区域");
        return;
      },
      deleteSubItem: function () {
        var formData = cn.getCurTabForm();
        var tableArr = formData.cellPlus.formObj.tableArr;
        var cp = formData.cellPlus;
        var sel = cp.selection();

        for (var i = 0; i < tableArr.length; i++) {
          if (tableArr[i].tableType == 2) {
            var htRg = "RD:HTRG:" + tableArr[i].oid;
            htRg = cp.getRangeByCustomVar(htRg);
            if (htRg.isRgInThis(sel)) {
              var delRet = htRg.htRgDeleteItem(sel, null, function (retCom) {
                var curRg = retCom.curHTRgOne;
                var offsetArr = retCom.offsetArr;
                var headRg = retCom.headRg;
                var newOne = curRg.cloneNew();
                var did = newOne.genOffsetRg(offsetArr[0]).tag();
                var tableId = tableArr[i].oid;
                var ret = yddser.delSubTableData(tableId, did);
                if (ret.code != 0) {
                  cm.showFailedDlg(ret.msg);
                  return 0;
                }
                return 1;
              });
              return;
            }
          }
        }

        $('#my-alert .am-modal-bd').text('未发现子表数据区域');
        $('#my-alert').modal();
        return;
      },
      getData: function (num) {
        var formData = cn.getCurTabForm();
        var ret = yddser.findDataByDate(formData.cellPlus.formObj.oid, num);
        cm.forEach(ret.data, function (obj) {
          obj['更新时间'] = cm.dtToLYMDMS(obj.updateTime);
        });
        this.gridColumns = cn.getDataKeyCols(ret.data[0]);
        this.gridData = ret.data
        //cache data
        var tmpData = formData.cellPlus.tmpData;
        tmpData.quickDateNum = num;
        tmpData.quickData = ret.data;
      }
    }
  });

  var auth = null;
  var authed = false;

  function showDeptUserModal(inData, func, inState) {

    var retData = yddser.getDept("all", true);
    var retUser = yddser.getUser2("all", 1, 1);

    // 设置数据  auth.$data.users = [],   auth.$data.departments = []
    var auth = new Vue({
      el: '#authorize-users-confirm',
      data: {
        state: inState,
        deptId: '',
        users: retUser.data,
        departments: [],
        selDept: [],
        selUser: [],
      },
      methods: {
        deselectUser: function (user) {
          user.selected = false;
        },
        deselectDepartment: function (department) {
          department.selected = false;
          $('#department-select').jstree(true).deselect_node(department.id)
        },
        save: function () {
          var uCount = 0;
          for (var i = 0; i < this.users.length; i++) {
            if (this.users[i].selected) {
              this.selUser.push(this.users[i]);
            }
          }
          var dCount = 0;
          for (var i = 0; i < this.departments.length; i++) {
            if (this.departments[i].selected) {
              this.selDept.push(this.departments[i]);
            }
          }
          if (func != null) {
            func(inData, this.selDept, this.selUser);
          }
        },
        cancel: function () {
          this.selDept = [];
          this.selUser = [];
        }
      }
    });

    $('#authorize-users-confirm').modal();
    if (!authed) {
      authed = true;

      $('#departments').on('select_node.jstree', function (node, ele) {
        auth.$data.deptId = ele.node.original.oid;
      }).jstree({
        'core': {
          'multiple': false,
          'check_callback': true,
          'data': retData.data,
        },
        "types": {
          "#": {"max_children": 1, "max_depth": 4, "valid_children": ["company"]},
          "department": {"icon": "../main/img/department.png", "valid_children": ["default"]},
          "default": {"valid_children": ["default", "file"]},
          "company": {"icon": "../main/img/company.png", "valid_children": ["department"]}
        },
        "search": {
          "show_only_matches": true
        },
        "plugins": ["types", "wholerow", "search"]
      });


      $('#department-select').on('ready.jstree', function () {
        var data = $('#department-select').jstree(true)._model.data;
        for (key in data) {
          var node = data[key];
          auth.$data.departments.push({
            id: node.id, name: node.text, selected: false,
            deptCode: node.original != null ? node.original.deptCode : ""
          });
        }
      }).on('changed.jstree', function (node, selected) {
        for (var i = 0; i < auth.$data.departments.length; i++) {
          if (selected.selected.indexOf(auth.$data.departments[i].id) == -1) {
            auth.$data.departments[i].selected = false;
          } else {
            auth.$data.departments[i].selected = true;
          }
        }
      }).jstree({
        'core': {
          'multiple': true,
          'check_callback': true,
          'data': retData.data,
        },
        "types": {
          "#": {"max_children": 1, "max_depth": 4, "valid_children": ["company"]},
          "department": {"icon": "../main/img/department.png", "valid_children": ["default"]},
          "default": {"valid_children": ["default", "file"]},
          "company": {"icon": "../main/img/company.png", "valid_children": ["department"]},
        },
        'checkbox': {
          three_state: false
        },
        "plugins": ["types", "wholerow", "checkbox"]
      });
    }

  }


  $('#authorize-users').click(function () {
    showDeptUserModal(null, null, 'all');
  });


  var btPop = new Vue({
    el: '#business-tooltips',
    data: {
      showBtns: true,
      isAddReport: false,
      nodeId: '',
      curNode: {},
      btName: '',
      placeHolder: ''
    },
    methods: {
      editName: function () {
        this.showBtns = false;
        this.isAddReport = false;
        if (this.isPackage) {
          this.placeHolder = '请输入业务包名称';
        } else {
          this.placeHolder = '请输入表单名称';
        }
        var inputele = this.$el.getElementsByTagName('input');
        setTimeout(function () {
          inputele[0].focus();
          console.log(inputele[0]);
        }, 0);
      },
      addReport: function () {
        this.showBtns = false;
        this.isAddReport = true;
        this.placeHolder = '请输入表单名称';
        var inputele = this.$el.getElementsByTagName('input');
        setTimeout(function () {
          inputele[0].focus();
          console.log(inputele[0]);
        }, 0);
      },
      newReportData: function () {
        this.$el.style.display = 'none';
        var CurrentNode = this.curNode;
        var oidv = CurrentNode.original.oid;

        var retD = yddser.getFormTmplList(oidv, 1, 0, 0);
        if (cm.dataNotOk(retD)) {
          cm.myAlert(retD.msg);
          return;
        }
        formTmpl.$data.imgs = retD.data;
        $('#new-report-data').show();
      },
      save: function () {
        var CurrentNode = this.curNode;
        var oidv = CurrentNode.original.oid;
        var obj = {};

        if (this.isAddReport) {
          obj.packId = oidv;
          obj.name = this.btName;
          var retD = yddser.addOrUpdateForm(obj);
          cn.yddToJstree(retD.data);
          if (cm.dataOk(retD)) {
            $('.cube_dimension_tree').jstree(true).create_node(CurrentNode, retD.data, 'first');
          }
        }
        else if (this.isPackage) {
          obj.oid = oidv;
          obj.name = this.btName;
          var retD = yddser.addOrUpdatePack(obj);
          if (cm.dataOk(retD)) {
            CurrentNode.original.name = this.btName;
            $('.cube_dimension_tree').jstree(true).rename_node(CurrentNode, this.btName);
          }
        }
        else {
          obj.oid = oidv;
          obj.name = this.btName;
          var retD = yddser.addOrUpdateForm(obj);
          if (cm.dataOk(retD)) {
            CurrentNode.original.name = this.btName;
            $('.cube_dimension_tree').jstree(true).rename_node(CurrentNode, this.btName);
          }
        }
        this.btName = '';
        this.$el.style.display = 'none';
      },
      delete: function () {
        $('#delete-confirm .am-modal-hd').text('确定要删除 "' + this.curNode.original.name + '" 这条记录吗？');
        $('#delete-confirm').modal({
          relatedTarget: this,
          curNode: this.curNode,
          onCancel: function (e) {
          },
          onConfirm: function (e) {
            var CurrentNode = $('.cube_dimension_tree').jstree(true).get_selected(true);
            var ret = null;
            if (cm.strStartWith(this.relatedTarget.curNode.original.oid, 'fm')) {
              ret = yddser.delForm(this.relatedTarget.curNode.original.oid);
            } else if (cm.strStartWith(this.relatedTarget.curNode.original.oid, 'pk')) {
              ret = yddser.delPack(this.relatedTarget.curNode.original.oid);
            }
            if (cm.dataOk(retD)) {
              $('.cube_dimension_tree').jstree(true).delete_node(this.relatedTarget.curNode);
            }
          }
        });
      },
      cancel: function () {
        this.$el.style.display = 'none';
      }
    },
    computed: {
      isPackage: function () {
        return this.nodeId.slice(0, 2) == 'pk';
      }
    }
  });

  $(".dropdown-finddata").on('open.dropdown.amui', function (e) {
    workspace_toolbar.$data.gridColumns = [];
    workspace_toolbar.$data.gridData = [];
    workspace_toolbar.$data.quickDateNum = 0;
    var formData = cn.getCurTabForm();
    var tmpData = formData.cellPlus.tmpData;
    if (tmpData.quickData != null) {
      cm.forEach(tmpData.quickData, function (obj) {
        obj['更新时间'] = cm.dtToLYMDMS(obj.updateTime);
      });
      workspace_toolbar.$data.gridColumns = cn.getDataKeyCols(tmpData.quickData[0]);
      workspace_toolbar.$data.gridData = tmpData.quickData;
      workspace_toolbar.$data.quickDateNum = tmpData.quickDateNum;
    }
  });

  $('.dropdown-mouse-class').on('mouseleave', function (e) {
    //var $dropdown = $(e.currentTarget);
    //data = $dropdown.data('amui.dropdown');
    //if (data.active) {
    //    $dropdown.dropdown('close');
    //}
  }).on('mouseenter', function (e) {
    //var $dropdown = $(e.currentTarget);
    //data = $dropdown.data('amui.dropdown');
    //if (!data.active) {
    //    $dropdown.dropdown('open');
    //}
  });

  var filterData = {};
  cn.tabClose = function (shell, tab) {
    var tabD = tab.data('tabData').data;
    cn.deleteFormDiv(tabD);
    chromeTabs.closeTab(shell, tab);

    $currentTab = $('.chrome-tabs-shell').find('.chrome-tab-current');
    if ($currentTab.data('tabData') == null) {
    }
    else {
      cn.hideFormDiv($currentTab.data('tabData').data, false);
    }

    var formId = tabD.id;
    if (filterVue.$data.tabId == formId) {
      filterVue.$data.tabId = '';
      filterVue.$data.tabData = {};
    }
    delete filterData[formId];
  }

  var $chromeTabsExampleShell = $('.chrome-tabs-shell')
  $chromeTabsExampleShell.bind('chromeTabRender', function () {
    if (cn.getCurTabForm() != null) {
      var formId = cn.getCurTabForm().id;
      if (filterVue.$data.tabId != formId) {
        if (filterData[formId] != null && filterData[formId].show) {
          filterVue.$data.tabId = formId;
          filterVue.$data.tabData = filterData[formId];
          filterVue.$el.style.display = 'block';
        } else {
          filterVue.$el.style.display = 'none';
        }
      } else if (filterVue.$data.tabData.show) {
        filterVue.$el.style.display = 'block';
      }
    } else {
      filterData = {};
      filterVue.$el.style.display = 'none';
      $('.workspace_toolbar').hide();
      $('.chrome-tabs-shell').hide();
      $('.container').css('background', 'url(../main/newLogin_files/resources/images/bg.jpg) no-repeat');
    }
  });

  $('#filter-reports').click(function () {
    var formData = cn.getCurTabForm();
    if(filterVue.$data.tabId == formData.id) {
      if(filterVue.$el.style.display == 'block') {
        filterVue.$el.style.display = 'none';
        filterVue.$data.tabData.show = false;
      } else {
        filterVue.$el.style.display = 'block';
        filterVue.$data.tabData.show = true;
      }
      return;
    }
    var findArr = yddser.getFormFindArr(formData.id);
    if (cm.dataNotOk(findArr)) {
      cm.myAlert(findArr.msg);
      return;
    }
    if (filterData[formData.id] == null) {
      filterData[formData.id] = {
        show: true,
        fields: [
          {
            fieldNameEx: '创建人',
            fieldTypeEx: 'user-list',
            options: [{
              checked: false,
              name: '当前用户',
              icon: 'https://o1aqprei7.qnssl.com/assets/images/avatar/user.jpg'
            }, {
              checked: false,
              name: 'Stefan',
              icon: 'https://hb-v4-public-img.huoban.com/user_avatar/7011488/0@128w_128h_1l'
            }, {
              checked: false,
              name: '丽丽',
              icon: 'https://hb-v4-public-img.huoban.com/user_avatar/7011488/0@128w_128h_1l'
            }],
            show: false
          },
          {
            fieldNameEx: '创建时间',
            fieldTypeEx: 'date',
            options: [{checked: false, name: '今天'}, {checked: false, name: '昨天'}, {
              checked: false,
              name: '过去7天'
            }, {checked: false, name: '过去30天'}, {checked: false, name: '本月'}, {
              checked: false,
              name: '上月'
            }, {checked: false, name: '本季度'}, {checked: false, name: '上季度'}, {
              checked: false,
              name: '自定义'
            }],
            show: false,
            startDate: '',
            endDate: ''
          },
          {
            fieldNameEx: '职业',
            fieldTypeEx: 'text',
            options: [],
            value: '',
            show: false,
            filled: false,
            notfilled: false
          },
          {
            fieldNameEx: '自我介绍',
            fieldTypeEx: 'text',
            options: [],
            value: '',
            show: false,
            filled: false,
            notfilled: false
          },
          {
            fieldNameEx: '是否已婚',
            fieldTypeEx: 'list',
            options: [{checked: false, name: '是'}, {checked: false, name: '否'}],
            value: '',
            show: false
          },
          {
            fieldNameEx: '兴趣爱好',
            fieldTypeEx: 'multi-list',
            options: [{checked: false, name: '打游戏'}, {checked: false, name: '踢足球'}, {
              checked: false,
              name: '打篮球'
            }, {checked: false, name: '游泳'}, {checked: false, name: '爬山'}, {
              checked: false,
              name: '跑步'
            }, {checked: false, name: '钓鱼'}, {checked: false, name: '看书'}, {
              checked: false,
              name: '下象棋'
            }],
            value: '',
            show: false
          }
        ],
        result: {
          headers: ['fieldNameEx', 'fieldTypeEx', 'value', 'age', 'gender', 'salary', 'actions'],
          items: []
        }
      }
    }

    filterData[formData.id].fields = findArr.data;
    filterVue.$data.tabId = formData.id;
    filterVue.$data.tabData = filterData[formData.id];
    filterVue.$data.tabData.show = true;
    filterVue.$el.style.display = 'block';
  });

  var filterVue = new Vue({
    el: '#filter-panel',
    data: {
      tabId: '',
      tabData: {
        show: true,
        fields: [],
        result: {
          headers: [],
          items: []
        }
      }
    },
    methods: {
      toggle: function (field) {
        field.show = !field.show;
      },
      selectOption: function (field, opt, multi) {
        opt.checked = !opt.checked;
        if (!multi) {
          for (var i = 0; i < field.options.length; i++) {
            if (field.options[i] != opt) {
              field.options[i].checked = false;
            }
          }
        }
      },
      showStartDatePicker: function (field) {
        for (var i = 0; i < field.options.length; i++) {
          if (field.options[i].name != '自定义') {
            field.options[i].checked = false;
          } else {
            field.options[i].checked = true;
          }
        }
        var target = event.target;
        if (!$(target).data('datepicker')) {
          $(target).datepicker().on('changeDate.datepicker.amui', function (event) {
            field.startDate = event.date.getFullYear() + '-' + (event.date.getMonth() + 1) + '-' + event.date.getDate();
            $(this).datepicker('close');
          });

          $(target).data('datepicker', true);
        }
      },
      showEndDatePicker: function (field) {
        for (var i = 0; i < field.options.length; i++) {
          if (field.options[i].name != '自定义') {
            field.options[i].checked = false;
          } else {
            field.options[i].checked = true;
          }
        }
        var target = event.target;
        if (!$(target).data('datepicker')) {
          $(target).datepicker().on('changeDate.datepicker.amui', function (event) {
            field.endDate = event.date.getFullYear() + '-' + (event.date.getMonth() + 1) + '-' + event.date.getDate();
            $(this).datepicker('close');
          });

          $(target).data('datepicker', true);
        }
      },
      toggleFilled: function (field) {
        field.filled = !field.filled;
        if (field.filled) {
          field.notfilled = false;
        }
      },
      toggleNotFilled: function (field) {
        field.notfilled = !field.notfilled;
        if (field.notfilled) {
          field.filled = false;
        }
      },
      filterField: function (field) {
        console.log(field.value);
      },
      open: function (field) {
        var curTab = cn.getCurTabForm();
        var tabData = cellDgnEvent.openFormById(null, curTab.id);
        var reqResData = yddser.getFormData(field.dataIndex).data;
        cn.resetForm(tabData.cellPlus);
        cn.setCplFormData(tabData.cellPlus, reqResData);
        this.cancel();
      },
      cancel: function () {
        this.tabData.show = false;
        this.$el.style.display = 'none';
      },
      save: function () {
        var retD = yddser.findDataByFindArr(this.tabId, this.tabData.fields, -1, -1);
        if (cm.dataNotOk(retD)) {
          cm.myAlert(retD.msg);
          return;
        }
        this.tabData.result.items = retD.data;
      }
    }
  });

  var formTmpl = new Vue({
    el: '#new-report-data',
    data: {
      imgs: [
        {
          createTime: null,
          dateIndex: '',
          formId: '',
          oid: '0',
          packId: '',
          tableId: '',
          tmplImage: '',
          tmplDesc: 'this is for something big...',
          tmplName: 'Template 1',
          updateTime: '',
          userId: ''
        },
        {
          createTime: null,
          dateIndex: '',
          formId: '',
          oid: '1',
          packId: '',
          tableId: '',
          tmplImage: '',
          tmplDesc: 'just the description for template.....',
          tmplName: 'Template 2',
          updateTime: '',
          userId: ''
        },
        {
          createTime: null,
          dateIndex: '',
          formId: '',
          oid: '2',
          packId: '',
          tableId: '',
          tmplImage: '',
          tmplDesc: 'just the description for template.....',
          tmplName: 'Template 3',
          updateTime: '',
          userId: ''
        },
        {
          createTime: null,
          dateIndex: '',
          formId: '',
          oid: '3',
          packId: '',
          tableId: '',
          tmplImage: '',
          tmplDesc: 'just the description for template.....',
          tmplName: 'Template 4',
          updateTime: '',
          userId: ''
        },
      ]
    },
    methods: {
      closeTemplate:function(){
        this.$el.style.display = 'none';
      },
      openTemplate: function (tid) {
        var retD = yddser.getFormTmpl(tid);
        if (cm.dataNotOk(retD)) {
          cm.myAlert(retD.msg);
        }

        var tabD = cn.genTabData("", retD.data.tmplName, {type: 'local', id: retD.data.oid});
        var cp = cn.addTab(tabD);
        cp.loadFromJsonStr(retD.data.formObj.styleData);
        cp.formObj = retD.data.formObj;
        delete retD.data.formObj;
        cp.formTmpl = retD.data;
        cn.setCplFormTableArrPos(cp, function (cpsheet) {
          cpsheet.readonly(true);
        }, function (cprg) {
          cprg.readonly(false);
        });

        var reqResData = retD.data.dataObj;
        delete retD.data.dataObj;
        cn.setCplFormData(cp, reqResData);
        this.closeTemplate();
      }
    }
  })
});